package sample.controller;

import javafx.application.Platform;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.VBox;
import javafx.stage.WindowEvent;
import sample.context.Context;
import sample.context.ContextValues;
import sample.context.StageManager;
import sample.pojo.User;
import sample.util.ChatReceive;
import sample.util.ChatSent;
import sample.util.DataSave;
import sample.util.NetUtil;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author ：five03
 * @description：TODO
 * @date ：2020/8/12 4:10 下午
 */

public class MainController {

    @FXML
    private Label adminUsername;

    @FXML
    private Label adminIP;

    @FXML
    private Label UserInfo;

    @FXML
    private TextArea inputTextField;

    @FXML
    private TextField addUserField;

    @FXML
    private ListView<String> outputTestList;

    @FXML
    private ListView<String> UserList;

    @FXML
    private VBox leftVBox;

    @FXML
    private AnchorPane leftPane;

    @FXML
    private VBox rightVBox;

    @FXML
    private AnchorPane rightPane;

    // 数据初始化
    @FXML
    public void initialize() {
        // 将本控制器放至管理台
        StageManager.CONTROLLER.put("MainController", this);
        adminUsername.setText("欢迎！" + ContextValues.adminUserName);
        adminIP.setText("本机IP地址: " + ContextValues.hostIp);
        refreshUserList();
        selectUserListener();
        sentTestListener();
        new ChatReceive().start();

        // 动态宽度绑定
        leftVBox.prefWidthProperty().bind(leftPane.widthProperty());
        addUserField.prefWidthProperty().bind(leftPane.widthProperty());
        rightVBox.prefWidthProperty().bind(rightPane.widthProperty());
        outputTestList.prefWidthProperty().bind(rightPane.widthProperty());
        inputTextField.prefWidthProperty().bind(rightPane.widthProperty());

    }

    // 退出
    @FXML
    void logoutCharROOM(ActionEvent event) {
        StageManager.STAGE.get("MainView").close();
        //删除map中的引用
        StageManager.STAGE.remove("MainView");
        StageManager.CONTROLLER.remove("loginControl");

        System.out.println("===>用户登录退出");

        // 移除本机用户 清空广播聊天记录
        Context.USERS.remove(ContextValues.hostIp);
        Context.USERS.get(ContextValues.strangerIP).clearChattingRecord();

        ChatSent.sendUserReq("0",ContextValues.hostIp,ContextValues.port);

        StageManager.STAGE.get("LoginView").show();
    }

    // 添加好友
    @FXML
    void addUser(ActionEvent event) {
        String userIP = addUserField.getText();
        if(checkIp(userIP)){
            String s = ContextValues.addUserCode + "@" + ContextValues.adminUserName + "@" + ContextValues.hostIp;
            ChatSent.sendUserReq(s,userIP,ContextValues.port);
        }
    }

    // 保存聊天记录
    @FXML
    void logChattingRecords(ActionEvent event) {
        for(User user : Context.USERS.values()){
            for(String s : user.readChattingRecord()){
                DataSave.writeChattingRecords("\n" + s + "\n");
            }
        }
    }

    // 搜索附近的人
    @FXML
    void searchUser(ActionEvent event) {
        String s = ContextValues.addUserCode + "@" + ContextValues.adminUserName + "@" + ContextValues.hostIp;
        ChatSent.sendUserReq(s,ContextValues.strangerIP,ContextValues.port);

    }

    // 发送消息
    void sentTestListener() {
        // 发送框监听
        inputTextField.setOnKeyPressed(new EventHandler<KeyEvent>() {
            @Override
            public void handle(KeyEvent ke) {
                if (ke.getCode().equals(KeyCode.ENTER)) {
                    String text = inputTextField.getText().trim();

                    if (text.isEmpty()) return;

                    if (Context.NOWCHATING.getIP().equals(ContextValues.strangerIP)){
                        ChatSent.sendStrangerText(text, ContextValues.strangerIP, ContextValues.port);
                    }else {
                        // 私聊对话框
                        ChatSent.sendText(text, Context.NOWCHATING.getIP(), ContextValues.port);
                        // 保存发送信息聊天记录
                        String s = Context.getDate() + "\t我: " + "\n" + text + "\n";
                        Context.NOWCHATING.saveChattingRecord(s);
                    }

                    refreshOutputTextList();

                    inputTextField.clear();
                }
            }
        });
    }

    // 刷新好友列表
    public void refreshUserList() {
        Platform.runLater(() -> {
            ObservableList<String> strList = FXCollections.observableArrayList(Context.getUsers());
            UserList.setItems(strList);
            System.out.println("===>好友列表刷新");
        });
    }

    // listView 控件监听
    void selectUserListener() {
        UserList.getSelectionModel().selectedItemProperty().addListener(
                (ObservableValue<? extends String> observable, String oldValue, String newValue) -> {
                    User user = Context.getUser(newValue);
                    if (user != null) {
                        Context.NOWCHATING = user;
                        UserInfo.setText(newValue);
                        refreshOutputTextList();
                    }
                });
    }

    // 刷新消息
    public void refreshOutputTextList() {
        Platform.runLater(() -> {
            ObservableList<String> strList = FXCollections.observableArrayList(Context.NOWCHATING.readChattingRecord());
            outputTestList.setItems(strList);
            System.out.println("===>聊天窗口刷新");
        });
    }

    // 测试IP地址格式
    public static boolean checkIp(String ipAddress) {
        String ip = "([1-9]|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])(\\.(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3}";
        Pattern pattern = Pattern.compile(ip);
        Matcher matcher = pattern.matcher(ipAddress);
        return matcher.matches();
    }
}

